//
//  WechatManager.m
//  CCQMEnglish
//
//  Created by Roger on 2019/9/30.
//  Copyright © 2019 Roger. All rights reserved.
//

#import "WechatManager.h"
#import "UIImage+ImageCornerRadius.h"
#import "GSCurrentVC.h"

@implementation WechatPayModel

@end

typedef void(^completeWein)(NSString *code);//传参类型及形参
typedef void(^completeWeinUserInfo)(NSDictionary *userInfo);//传参类型及形参

@interface WechatManager ()
<WXApiDelegate,WXApiLogDelegate>
{
    NSString *WXAPPid;
    NSString *WXAppSecret;

}
@property(nonatomic, strong) completeWein block;
@property(nonatomic, strong) completeWeinUserInfo userInfoBlock;

@end
@implementation WechatManager

//非标准单例
static WechatManager *manager = nil;
+ (WechatManager *)defaultManager {
    @synchronized(self) {//同步 执行 防止多线程操作
        if (manager == nil) {
            manager = [[self alloc] init];
        }
    }
    return manager;
}
//配置
-(id)init{
    if (self = [super init]) {
        WXAPPid = @"wxb32cfa4f6d3254b6";
        WXAppSecret = @"";
    }
    return self;
}
-(void)wechatRegisterApp{
    
    [WXApi registerApp:WXAPPid];
    [WXApi startLogByLevel:1  logDelegate:self];
}
-(void)sendAuthRequest{
    //构造SendAuthReq结构体
       SendAuthReq * req = [[SendAuthReq alloc]init];
       req.scope = @"snsapi_userinfo";
       req.state = @"wx_oauth_authorization_state";
       //第三方向微信终端发送一个SendAuthReq消息结构
       [WXApi sendReq:req];
}
-(void)sendAuthRequestComplete:(void (^)(NSString * wechatCode))complete
{
    [self sendAuthRequest];
    self.block = ^(NSString *code) {
         complete(code);
    };

}
-(void)openWeChatIdComplete:(void (^)(NSDictionary * wechatUserInfo))complete
{
    [self sendAuthRequest];
    self.userInfoBlock = ^(NSDictionary *userInfo) {
        complete(userInfo);
    };

}
#pragma mark - Delegate
-(void)onReq:(BaseReq *)req{
    GSLog(@"BaseReq:%@",req);
    ShowMessageFromWXReq* temp = (ShowMessageFromWXReq*)req;
    WXMediaMessage *msg = temp.message;

    //显示微信传过来的内容
    WXAppExtendObject *obj = msg.mediaObject;
    GSLog(@"BaseReq:%@",obj);
}
-(void)onResp:(BaseResp *)resp{
    if([resp isKindOfClass:[SendAuthResp class]]){//判断是否为授权登录类

        SendAuthResp *req = (SendAuthResp *)resp;

        if([req.state isEqualToString:@"wx_oauth_authorization_state"]){//微信授权成功
            //req.code; //获得code
            
            NSString *code = req.code;
            GSLog(@"req.code:%@",code);//
            if (self.block) {//先判断
                self.block(code);
            }
           //授权成功获取 OpenId
            [self getWeiXinOpenId:code];
        }
        GSLog(@"BaseResp:%d - %@",resp.errCode,resp.errStr);
    }
    if ([resp isKindOfClass:[WXLaunchMiniProgramResp class]])
    {
        GSLog(@"%@",resp.errStr);
        // 对应JsApi navigateBackApplication中的extraData字段数据
    }
    //微信支付回调
    NSString *strMsg,*strTitle = [NSString stringWithFormat:@"支付结果"];
    if ([resp isKindOfClass:[PayResp class]]){
            PayResp*response=(PayResp*)resp;
            switch(response.errCode){
                WXSuccess:
                {
                    //服务器端查询支付通知或查询API返回的结果再提示成功
                   strMsg = @"支付结果:成功!";
                   GSLog(@"%@－PaySuccess，retcode = %d",strMsg, resp.errCode);
                }
                    break;
                default:
                    strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                    GSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                  break;
            }
        [[GSLAlertView alertManager] createInitWithTitle:strTitle message:strMsg sureBtn:@"知道了" cancleBtn:nil];
        [[GSLAlertView alertManager] showGSAlertView];
      }
    
//    // =============== 获得的微信登录授权回调 ============
//       if ([resp isMemberOfClass:[SendAuthResp class]])  {
//           NSLog(@"******************获得的微信登录授权******************");
//
//           SendAuthResp *aresp = (SendAuthResp *)resp;
//           if (aresp.errCode != 0 ) {
//               dispatch_async(dispatch_get_main_queue(), ^{
////                   [self showError:@"微信授权失败"];
//               });
//               return;
//           }
//           //授权成功获取 OpenId
//           NSString *code = aresp.code;
//           [self getWeiXinOpenId:code];
//       }
//       // =============== 获得的微信支付回调 ============
//       if([resp isKindOfClass:[PayResp class]]){
//           //支付返回结果，实际支付结果需要去微信服务器端查询
//       }
}
-(void)onLog:(NSString *)log logLevel:(WXLogLevel)level{
    GSLog(@"Wechar_log:%@",log);
}
//通过code获取access_token，openid，unionid
- (void)getWeiXinOpenId:(NSString *)code{
    /*
     appid    是    应用唯一标识，在微信开放平台提交应用审核通过后获得
     secret    是    应用密钥AppSecret，在微信开放平台提交应用审核通过后获得
     code    是    填写第一步获取的code参数
     grant_type    是    填authorization_code
     */
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WXAPPid,WXAppSecret,code];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data1 = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        
        if (!data1) {
//            [self showError:@"微信授权失败"];
            return ;
        }
        
        // 授权成功，获取token、openID字典
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"token、openID字典===%@",dic);
        NSString *access_token = dic[@"access_token"];
        NSString *openid= dic[@"openid"];
        
        //         获取微信用户信息
        [self getUserInfoWithAccessToken:access_token WithOpenid:openid];
        
    });
}
-(void)getUserInfoWithAccessToken:(NSString *)access_token WithOpenid:(NSString *)openid
{
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",access_token,openid];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            // 获取用户信息失败
            if (!data) {
//                [self showError:@"微信授权失败"];
                return ;
            }
            
            // 获取用户信息字典
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //用户信息中没有access_token 我将其添加在字典中
            [dic setValue:access_token forKey:@"token"];
            NSLog(@"用户信息字典:===%@",dic);
            //保存改用户信息(我用单例保存)
            self.weiXinIfon = dic;
          //微信返回信息后,会跳到登录页面,添加通知进行其他逻辑操作
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"weiChatOK" object:nil];
            if (self.userInfoBlock) {
                self.userInfoBlock(dic);
            }
        });
        
    });
    
}

#pragma mark - 微信支付
-(void)wechat_pay:(WechatPayModel *)model{
    PayReq *pay = [[PayReq alloc] init];
    pay.partnerId = model.partnerId;
    pay.prepayId = model.prepayId;
    pay.package = model.package;
    pay.nonceStr = model.nonceStr;
    pay.timeStamp = model.timeStamp;
    pay.sign = model.sign;
    [WXApi sendReq:pay];
}
#pragma mark - 设置代理回调
-(BOOL)new_handleOpenURL:(NSURL *)url{
  return  [WXApi handleOpenURL:url delegate:self];
}
-(BOOL)new_handleOpenUniversalLink:(NSUserActivity *)userActivity{
  return  [WXApi handleOpenUniversalLink:userActivity delegate:self];
}
#pragma mark - 分享链接到微信
-(void)shareWeChatLink:(NSString *)url description:(NSString *)description title:(NSString *)title image:(UIImage *)image Scene:(int)scene{
    if ([WXApi isWXAppInstalled] && [WXApi isWXAppSupportApi]) {
//        NSData *imageData = UIImageJPEGRepresentation(image, 1);
        UIImage *thumbImage = [UIImage imageWithData:UIImageJPEGRepresentation( [image compressToByte:1024*6], 0.5)];
        SendMessageToWXReq * req = [[SendMessageToWXReq alloc] init];
        WXMediaMessage * message = [[WXMediaMessage alloc] init];
        WXWebpageObject * ext = [[WXWebpageObject alloc] init];
        //需要分享的链接
        ext.webpageUrl = url;//多媒体数据对象
        message.mediaObject = ext;
        //分享的链接介绍文本
        message.description = description;//分享的链接标题
        message.title = title;//给分享链接设置小图标
        [message setThumbImage:thumbImage];
        //标记不是分享文本
         req.bText=NO;
        //设置message对象
         req.message = message;//分享目标场景
        //发送到聊天界面WXSceneSession = 0
        //发送到朋友圈WXSceneTimeline = 1
        //发送到微信收藏WXSceneFavorite
        req.scene = scene;
        //发起微信分享
        [self sendReq:req];
    }else {
            // 提示用户安装微信
             [self showAlert];
    }
}
#pragma mark - 分享图片到微信
- (void)WXSendImage:(UIImage *)image withShareScene:(enum WXScene)scene {
    if ([WXApi isWXAppInstalled] && [WXApi isWXAppSupportApi]) {
    
        NSData *imageData = UIImageJPEGRepresentation(image, 1);
        UIImage *thumbImage = [UIImage imageWithData:UIImageJPEGRepresentation( [image compressToByte:1024*6], 0.5)];
        
        WXImageObject *ext = [WXImageObject object];
        // 小于10MB
        ext.imageData = imageData;
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.mediaObject = ext;
        //    message.messageExt = @"";
        //    message.messageAction = @"";
        //    message.mediaTagName = @"";
        // 缩略图 小于32KB
        [message setThumbImage:thumbImage];
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.scene = scene?:0;
        req.message = message;
        [WXApi sendReq:req];
    }else {
        // 提示用户安装微信
         [self showAlert];
    }
}
#pragma mark - 分享小程序方法
-(void)share_WXMiniPath:(NSString *)path
               userName:(NSString *)userName
        miniProgramType:(NSInteger)miniProgramType
               msgTitle:(NSString *)title
            description:(NSString *)description
              thumImage:(NSString *)thumImage
{
    
    if ([WXApi isWXAppInstalled]) {
        id img ;
        if (thumImage) {
            if([thumImage rangeOfString:@"http"].location !=NSNotFound || [thumImage rangeOfString:@"https"].location !=NSNotFound){
                UIImage * image = [UIImage getImageFromURL:thumImage];
                img = [image compressToByte:1024*6];
            }else{
                img = [UIImage imageNamed:thumImage];
            }
        }else{
            img = [UIImage imageNamed:@"Logo"];
        }
        NSData *imageData = UIImageJPEGRepresentation(img,1.0f);//第二个参数为压缩倍数
        WXMiniProgramObject *object = [WXMiniProgramObject object];
        object.webpageUrl = @"http://www.qq.com";
        object.userName = userName;
        object.path = path;
        object.hdImageData = imageData;
        object.withShareTicket = YES;
        object.miniProgramType = miniProgramType;
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = title;
        message.description = description;
        message.thumbData = nil;  //兼容旧版本节点的图片，小于32KB，新版本优先
        //使用WXMiniProgramObject的hdImageData属性
        message.mediaObject = object;
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneSession;  //目前只支持会话
        [WXApi sendReq:req];
    }else{
        GSLog(@"您还未安装微信~");
       [self showAlert];
    }
}
#pragma mark - 移动应用跳转到小程序方法
-(void)open_WXMiniPath:(NSString *)path userName:(NSString *)userName
{
    [self open_WXMiniPath:path userName:userName miniProgramType:2];
}
-(void)open_WXMiniPath:(NSString *)path userName:(NSString *)userName miniProgramType:(NSInteger)miniProgramType{
    if ([WXApi isWXAppInstalled]) {
        WXLaunchMiniProgramReq * wxmini = [WXLaunchMiniProgramReq object];
        wxmini.userName = userName;
        wxmini.path = path;
        wxmini.miniProgramType = miniProgramType; //正式版:0，测试版:1，体验版:2
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendReq:wxmini];
    }else{
        GSLog(@"您还未安装微信~");
      [self showAlert];
    }

}
#pragma mark - 微信公众号
-(void)open_WXJumpToBizProfile{
    JumpToBizProfileReq *req = [JumpToBizProfileReq new];
    
    req.username = @"gh_6d67dd37db34"; // 原始ID
    
    req.profileType = WXBizProfileType_Normal;//这里还可以选择硬件公众号
    
    req.extMsg = @"";//选择硬件公众号，这里加入绑定设备的链接
    
    [WXApi sendReq:req];
    
}
#pragma mark - 打开微信网页
-(void)open_WechatWebWithUrl:(NSString *)url{
    OpenWebviewReq *req = [OpenWebviewReq new];
    req.url = @"需要微信内置浏览器打开的网址";
    [WXApi sendReq:req];
  
}
#pragma mark - 打开微信
-(void)open_Wechat{
    NSURL *new_url = [NSURL URLWithString:@"weixin://"];
    
    BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:new_url];
    
    if (canOpen) {
        
        [[UIApplication sharedApplication] openURL:new_url];
        
    }else{
        
        GSLog(@"未发现微信");
        [self showAlert];
    }
}
#pragma mark - alert
#pragma mark - tips 提醒
-(void)newTipsWithTitle:(NSString *)title message:(NSString *)message actionText:(NSString *)actionText{
       UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
                                                                      message:message
                                                               preferredStyle:UIAlertControllerStyleAlert];
       UIAlertAction *action = [UIAlertAction actionWithTitle:actionText
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action){
                                                          
                                                      }];
       [alert addAction:action];
       [[GSCurrentVC getCurrentVC] presentViewController:alert animated:YES completion:^{ }];
       
}

-(void)showAlert{
    [self newTipsWithTitle:@"提示" message:@"该功能需要微信操作，检测到您还未安装微信，请前往AppStore下载~" actionText:@"知道了"];
}
#pragma mark - 功能API
//市场推广小程序
-(void)open_wXMiniMarketing{
    [self open_WXMiniPath:[NSString stringWithFormat:@"pages/logining/logining"] userName:@"gh_4db0fa077000" miniProgramType:0];
}
//跳到微信小程序商户端
-(void)open_WXMiniShopId:(NSString *)shopId{
    [self open_WXMiniPath:[NSString stringWithFormat:@"/pages/index/index?id=%@",shopId] userName:@"gh_8a4165306efd"];
}
//跳到微信小程序工商注册
-(void)open_WXMiniRegBusiness{
    [self open_WXMiniPath:[NSString stringWithFormat:@"pages/phoneVerification/phoneVerifi?id=1"] userName:@"gh_33eee0551e01" miniProgramType:0];
}
//跳到 爷爷网微信公众号 工商注册
-(void)open_WXBizProfileRegBusiness{
    [self open_WXJumpToBizProfile];
}
//分享微信小程序商户端
-(void)share_WXMiniGoodsId:(NSString *)goodsId
                  traderId:(NSString *)traderId
                 goodsName:(NSString *)name
               description:(NSString *)description
                 thumImage:(NSString *)thumImage
{
  [self share_WXMiniPath:[NSString stringWithFormat:@"/pages/details/details?id=%@&traderId=%@",goodsId,traderId] userName:@"gh_8a4165306efd" miniProgramType:2 msgTitle:name description:description thumImage:thumImage];

}

-(void)share_WXMiniTraderId:(NSString *)traderId
                 goodsName:(NSString *)name
               description:(NSString *)description
                  thumImage:(NSString *)thumImage
{
        [self share_WXMiniPath:[NSString stringWithFormat:@"/pages/index/index?id=%@",traderId] userName:@"gh_8a4165306efd" miniProgramType:2 msgTitle:name description:description thumImage:thumImage];

}
//分享二维码到微信
-(void)share_WXpicWithImag:(UIImage *)image{
    [self WXSendImage:image withShareScene:0];
}


@end
